import { HttpClient } from '@angular/common/http';
import { Inject, Injectable, InjectionToken } from '@angular/core';

import { map } from 'rxjs/operators';

import { pb } from 'src/pb';

export const BROWSER_STORAGE = new InjectionToken<Storage>('Browser Storage', {
  providedIn: 'root',
  factory: () => localStorage
});

@Injectable({
  providedIn: 'root'
})
export class SettingsService {
  settings: any = {
    showDate: true,
    showSize: true,
    theme: 'vs-dark',
    language: 'text/plain',
    fontSize: 26,
    readOnly: true,
    wordWrap: 'on',
    autoRefresh: true,
    interval: 10,
    mouseWheelZoom: true,
  };
  config: pb.IConfig;
  constructor(
    @Inject(BROWSER_STORAGE)
    private storage: Storage,
    private http: HttpClient,
  ) {
    this.init();
    this.load();
  }
  save() {
    this.storage.setItem('settings', JSON.stringify(this.settings));
  }

  load() {
    const s = this.storage.getItem('settings');
    if (s) {
      Object.assign(this.settings, JSON.parse(s));
      this.settings.readOnly = true;
    }
  }

  private async init() {
    this.config = await this.http.get('/api/config', {
      responseType: 'arraybuffer'
    })
      .pipe(map(ab => pb.Config.decode(new Uint8Array(ab as ArrayBuffer))))
      .toPromise();
  }
}
